<?php
namespace app\api\controller\task;

use app\api\controller\Api;
use app\common\task\model\Device as PhoneDevice;
use app\common\task\validate\DeviceValidate;
use think\db\exception\DbException;
use util\Format;

class Device extends Api
{
    public function index()
    {
        $post = $this->request->post();

        $where = [];
        if (isset($post['keyword']) && !empty($post['keywords'])) $where[] = ['title', 'like', "%{$post['keywords']}%"];

        $model = new PhoneDevice();
        list($cfg) = Format::pagination($post);
        $pg = $model->where($where)->order('id')->paginate($cfg);
        $rows = $pg->getCollection();

        // 返回接口数据
        $result['list'] = $rows;
        $result['pagination'] = Format::pgResult($pg);

        return success($result, '获取数据成功');
    }



    public function read()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], '参数错误');

        $model = new PhoneDevice();
        $result['row'] = $model->where('id', $post['id'])->find();

        return success($result);
    }

    public function create()
    {
        $post = $this->request->post();
        // 创建的时候清除干扰的信息
        unset($post['id']);
        // 验证提交
        $validate = new DeviceValidate();
        if (!$validate->scene('create')->check($post)) return error([], $validate->getError());

        $model = new PhoneDevice();
        try {
            $model->save($post);
        } catch (DbException $e) {
            return error([], "添加设备失败");
        }

        return success([], '添加设备成功');
    }

    public function update()
    {
        $post = $this->request->post();

        // 验证提交
        $validate = new DeviceValidate();
        if (!$validate->scene('edit')->check($post)) return error([], $validate->getError());

        $model = new PhoneDevice();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '设备已不存在');

        $user = $this->request->user;
        $post['creator_id'] = $user['id'];
        $rs = $row->save($post);

        if ($rs) {
            return success([], '编辑设备信息成功');
        } else {
            return error([], '编辑设备信息失败');
        }
    }

    public function delete()
    {
        $post = $this->request->post();
        // 验证提交
        $validate = new DeviceValidate();
        if (!$validate->scene('delete')->check($post)) return error([], $validate->getError());

        $model = new PhoneDevice();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '设备已不存在');
        $rs = $row->delete();

        if ($rs) {
            return success([], '删除成功');
        } else {
            return error([], '删除失败');
        }
    }
}